package wzw.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import feign.RequestInterceptor;
import feign.RequestTemplate;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Wu Zhenwei
 * 2017/12/25
 */
public class UseObjectParamInGetMethodInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        if ("GET".equalsIgnoreCase(template.method())) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(template.body())));
            StringBuilder sb = new StringBuilder();
            String buf;
            try {
                while ((buf = reader.readLine()) != null) {
                    sb.append(buf);
                }
                JSONObject jsonObject = JSON.parseObject(sb.toString());
                jsonObject.forEach((key, value) -> {
                    if (value != null) {
                        template.query(key, value.toString());
                    }
                });
                template.body(null);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
